import 'package:flutter/material.dart';

class NumAnimate extends StatefulWidget {
  const NumAnimate({Key? key}) : super(key: key);

  @override
  _NumAnimateState createState() => _NumAnimateState();
}

class _NumAnimateState extends State<NumAnimate> {
  double _counte = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('数字计数器')),
      body: DefaultTextStyle.merge(
        style: const TextStyle(fontSize: 100),
        child: Center(
            child: SizedBox(
                // padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                width: 350,
                height: 120,
                child: AnimateCounter(
                  num: _counte,
                  duration: const Duration(seconds: 1),
                ))),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _counte++;
          });
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

class AnimateCounter extends StatelessWidget {
  final Duration duration;
  final double num;
  const AnimateCounter({Key? key, required this.duration, required this.num})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder(
        tween: Tween<double>(end: num),
        duration: duration,
        builder: (context, value, child) {
          int whole = value ~/ 1;
          double decimal = value - whole;
          return Stack(
            children: [
              Positioned(
                  top: -100 * decimal,
                  child: Opacity(opacity: 1 - decimal, child: Text('$whole'))),
              Positioned(
                  top: (1 - decimal) * 100,
                  child:
                      Opacity(opacity: decimal, child: Text('${whole + 1}'))),
            ],
          );
        });
  }
}
